#include "Directory.h"
#include "listdir.h"
#include "enginedirs.h"

namespace Lame3d
{
	Directory::Directory(const std::string &rPath, const char** goodExtensions)
			: dPath(rPath)
	{
		std::list<std::string> fList;
		std::list<std::string> gEList;
		if(goodExtensions != NULL) {
			while(*goodExtensions != NULL) {
				gEList.push_back(std::string(*goodExtensions));
				++goodExtensions;
			}
		}
		std::string sysPath = getSystemDir();
		sysPath += DIRSEP;
		sysPath += rPath;
		std::string userPath = getUserDir();
		userPath += DIRSEP;
		userPath += rPath;		
		listDirectory(sysPath, fList);
		listDirectory(userPath, fList);
		filterDirectory(fList, gEList);
		buildMap(fList);
	}
	
	Directory::Directory(const std::string &rPath, const std::list<std::string> &goodExtensions)
			: dPath(rPath)
	{
		std::list<std::string> fList;
		std::string sysPath = getSystemDir();
		sysPath += DIRSEP;
		sysPath += rPath;
		std::string userPath = getUserDir();
		userPath += DIRSEP;
		userPath += rPath;		
		listDirectory(sysPath, fList);
		listDirectory(userPath, fList);
		filterDirectory(fList, goodExtensions);
		buildMap(fList);
	}
	
	Directory::~Directory()
	{
		std::map<std::string, File*>::iterator it;
		printf("Pre-free summary:\n");
		for(it = files.begin(); it != files.end(); ++it) {
			printf("%s %s\n", it->first.c_str(), it->second->GetPath().c_str());
		}
		for(it = files.begin(); it != files.end(); ++it) {
			printf("Deleting %s (key: %s)...", it->second->GetPath().c_str(), it->first.c_str());
			delete it->second;
			printf("Deleted.\n");
		}
	}
	
	std::map<std::string, File*>::const_iterator Directory::FileIterator() const
	{
		return files.begin();
	}
	
	std::map<std::string, File*>::const_iterator Directory::End() const
	{
		return files.end();
	}
	
	File& Directory::operator[](const std::string pName)
	{
		File *file;
		std::map<std::string, File*>::iterator it;
		it = files.find(pName);
		if(it == files.end()) {
			std::string path(dPath);
			path += DIRSEP;
			path += pName;
			file = new File(path.c_str());
			files[pName] = file;
		} else {
			file = it->second;
		}
		return *file;
	}
	
	void Directory::buildMap(const std::list<std::string> &fList)
	{
		std::list<std::string>::const_iterator it;
		for(it = fList.begin(); it != fList.end(); ++it) {
			std::string path = dPath;
			path += DIRSEP;
			path += *it;
			//const std::string& path = *it;
			File *nF = new File(path.c_str());
			files[*it] = nF;
		}
	}
}

// eof
